package HuginnDatabase;
use strict;
use warnings;
use DBI;
require Exporter;
use HuginnConfiguration qw ( %Config );
our @ISA = qw(Exporter);
our @EXPORT_OK = qw( DatabaseOpen RowRotate ForEachRowToSend DatabaseClose SetRowSent SetRowError);


my %Query=
(
    DELETE => "delete from communications where TIMESTAMPDIFF($Config{DB_HISTORY_UNIT},LastStatusModified,Now()) > $Config{DB_HISTORY_UNIT_COUNT}",
    GET_TO_SEND => "select IDCommunication, Destination, Kind, Message, path_archivio from communications Where Status in ('to-send') order by IDCommunication;",
#   GET_TO_SEND => "select IDCommunication, Destination, Kind, Message, path_archivio from communications Where Status in ('to-send','error') order by IDCommunication;",
    ROW_STATUS_UPDATE => "update communications set status= ? , StatusMessage = ? where IDCommunication = ?",
);
my $DBConnection = undef;
sub DatabaseOpen()
{
    $DBConnection = DBI->connect($Config{DB_CNN_STR},
                                 $Config{DB_USER},
                                 $Config{DB_PASSWORD},
                                 {RaiseError=>1})
        or die "Connection Error";
}
sub RowRotate()
{
    die "Invalid connection object" unless $DBConnection;
    $DBConnection->do($Query{DELETE});
}
sub SetRowSent
{
    my ($id,$message) = @_;
    $message = $message || 'ok';
    SetRowStatus($id,'sent',$message);
    
}
sub SetRowError
{
    my ($id,$message) = @_;
    SetRowStatus($id,'error',$message);
}
sub SetRowStatus
{
    my ($id,$status,$message) = @_;
    while(chomp($message)) {}
    my $sth = $DBConnection->prepare($Query{ROW_STATUS_UPDATE});
    $sth->bind_param(1,$status);
    $sth->bind_param(2,$message);
    
    $sth->bind_param(3,$id);
    $sth->execute();
    $sth->finish();
}
sub ForEachRowToSend
{
    my $callback= shift;
    my ($Id,$Destination,$Kind,$Message,$path_archivio);
    my $sth = $DBConnection->prepare($Query{GET_TO_SEND});
    $sth->execute;
    $sth->bind_columns(undef,\$Id,\$Destination,\$Kind,\$Message,\$path_archivio);
    while($sth->fetch)
    {
        
        $callback->($Id,$Destination,$Kind,$Message,$path_archivio);
    }
    $sth->finish;
}

sub DatabaseClose()
{
    $DBConnection->disconnect if $DBConnection;
    $DBConnection = undef;
}
1;
